package com.fractalsbuilder.geom;


import javax.swing.*;
import java.awt.*;

public class Koch {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(300, 300);
        frame.setTitle("Koch");
        frame.add(new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D)g;
                drawKoch(g2, -1, 6, 0, 3 * getHeight() / 4, getWidth(), 3 * getHeight() / 4);
            }
        });
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static void drawKoch(final Graphics2D g2, int vector, int iteration, int x1, int y1, int x2, int y2) {
        if (iteration == 0) {
            g2.drawLine(x1, y1, x2, y2);
        } else {
            int a1 = (int)Math.round((x1 + x2) / 2 -vector * Math.sqrt(3) * (y2 - y1) / 6);
            int a2 = (int)Math.round(vector * Math.sqrt(3) * (x2 - x1) / 6 + (y1 + y2) / 2);
            drawKoch(g2, vector, iteration - 1, x1, y1, (2 * x1 + x2) / 3, (2 * y1 + y2) / 3);
            drawKoch(g2, vector, iteration - 1, (2 * x1 + x2) / 3, (2 * y1 + y2) / 3, a1, a2);
            drawKoch(g2, vector, iteration - 1, a1, a2, (x1 + 2 * x2) / 3, (y1 + 2 * y2) / 3);
            drawKoch(g2, vector, iteration - 1, (x1 + 2 * x2) / 3, (y1 + 2 * y2) / 3, x2, y2);
        }
    }

}
